package com.woniuxy.moneyapp.common.utils;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.nimbusds.jose.JWSObject;
import com.woniuxy.commons.config.AlipayConfig;
import com.woniuxy.commons.exception.MyException;
import com.woniuxy.commons.param.TransfesInfo;
import com.woniuxy.commons.util.*;
import java.text.ParseException;
import java.util.Date;

import com.woniuxy.moneyapp.common.exception.code.FundExceptionCode;
import com.woniuxy.moneyapp.doo.AccDto;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class CommonUtil {

    public static String simpleFormat(String str){
        String t = str.replaceAll("T", "");
        String s = t.replaceAll("-", "");
        String s1 = s.replaceAll(":", "");
        return  s1.replace(" ","");
    }

    public static String getRechargeCode(Integer code){
        if(code==1){
            //设置充值订单号
            String s = RandomUtil.randomNumbers(10);
            long l = System.currentTimeMillis();
            String s1 = DateUtil.timeFormatString(l, "yyyy-MM-dd HH:mm:ss");
            String s2 = CommonUtil.simpleFormat(s1);
            return "1"+s2+s;
        }
        if(code==0){
            //设置流水号
            String s = RandomUtil.randomNumbers(10);
            long l = System.currentTimeMillis();
            String s1 = DateUtil.timeFormatString(l, "yyyy-MM-dd HH:mm:ss");
            String s2 = CommonUtil.simpleFormat(s1);
            return "0"+s2+s;
        }
        if(code==3){
            //设置支付号
            String s = RandomUtil.randomNumbers(10);
            long l = System.currentTimeMillis();
            String s1 = DateUtil.timeFormatString(l, "yyyy-MM-dd HH:mm:ss");
            String s2 = CommonUtil.simpleFormat(s1);
            return "3"+s2+s;
        }
        if(code==4){
            //设置退款号
            String s = RandomUtil.randomNumbers(10);
            long l = System.currentTimeMillis();
            String s1 = DateUtil.timeFormatString(l, "yyyy-MM-dd HH:mm:ss");
            String s2 = CommonUtil.simpleFormat(s1);
            return "4"+s2+s;
        }
        if(code==2){
            //设置退款号
            String s = RandomUtil.randomNumbers(10);
            long l = System.currentTimeMillis();
            String s1 = DateUtil.timeFormatString(l, "yyyy-MM-dd HH:mm:ss");
            String s2 = CommonUtil.simpleFormat(s1);
            return "2"+s2+s;
        }
        throw new MyException(FundExceptionCode.NO_SCHEMA_CODE.getCode(),
                FundExceptionCode.NO_SCHEMA_CODE.getMsg()
                );
    }

    //trade_no支付宝交易号
    //refund_amount本次退款请求，对应的退款金额
    public static boolean refund(String out_trade_no, BigDecimal refund_amount) {
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, "RSA2");
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", out_trade_no);
        bizContent.put("refund_amount", refund_amount.toString());
        bizContent.put("out_request_no", System.currentTimeMillis() + "");

        // 返回参数选项，按需传入
//        JSONArray queryOptions = new JSONArray();
//        queryOptions.add("refund_detail_item_list");
//        bizContent.put("query_options", queryOptions);

        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        System.out.println(response.getRefundFee());
        if (response.isSuccess()) {
            System.out.println("调用成功");
            return true;
        } else {
            System.out.println("调用失败");
            return false;
        }
    }

    public static Result<String> Transfer(TransfesInfo transfesInfo) throws AlipayApiException {

        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl,AlipayConfig.app_id,AlipayConfig.merchant_private_key,"json",AlipayConfig.charset,AlipayConfig.alipay_public_key,"RSA2");

        AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
        request.setBizContent("{" +
                "  \"out_biz_no\":\""+TransferOrderRandom.createOrderSnRandom()+"\"," +
                "  \"payee_type\":\"ALIPAY_LOGONID\"," +
                "  \"payee_account\":\""+transfesInfo.getPayee_account()+"\"," +
                "  \"amount\":\""+transfesInfo.getAmount()+"\"," +
//                "  \"payer_real_name\":\"2088621958215041\"," +
//                "  \"payer_show_name\":\"测试\"," +
//                "  \"payee_real_name\":\"tgtygr0268\"," +
                "  \"remark\":\""+transfesInfo.getRemark()+"\"," +
                "  \"ext_param\":\"{\\\"order_title\\\":\\\""+transfesInfo.getOrder_title()+"\\\"}\"" +
                "}");
        AlipayFundTransToaccountTransferResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            System.out.println("转账唯一订单号"+response.getOutBizNo());
            System.out.println("调用成功");
            return  Result.getInstance(String.class).setCode(200).setData(response.getOutBizNo()).setMsg("转账成功");
        } else {
            System.out.println("调用失败");
            return  Result.getInstance(String.class).setCode(500).setMsg("转账失败");
        }
    }


    public static LocalDateTime transStrToLocalDateTime(String str){
       return LocalDateTime.parse(str,DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    public static String getCron(java.util.Date  date){
        String dateFormat="ss mm HH dd MM ? yyyy";
        return formatDateByPattern(date, dateFormat);
    }

    public static String formatDateByPattern(Date date, String dateFormat){
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        String formatTimeStr = null;
        if (date != null) {
            formatTimeStr = sdf.format(date);
        }
        return formatTimeStr;
    }

    public static AccDto getUserDto() throws ParseException {
        String token = WebUtil.getRequest().getHeader("Authorization");
        String realtoken = token.replace("Bearer " , "");
        JWSObject jwsObject = JWSObject.parse(realtoken);
        String userStr = jwsObject.getPayload().toString();
        return JSONObject.parseObject(userStr, AccDto.class);
    }

}
